/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.vdialog.model.instance;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ResourceBundle;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.text.Document;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import offset.nodes.Constants;
import offset.nodes.client.model.Server;
import offset.nodes.client.tree.model.DetailPanelTreeConfiguration;
import offset.nodes.client.tree.model.DetailPanelTreeConfiguration;
import offset.nodes.client.tree.model.TreeNodePanel;
import offset.nodes.client.tree.model.DetailPanelTreeNodeType;
import offset.nodes.client.model.TreeNodeUserObject;
import offset.nodes.client.virtual.model.jcr.SimpleNode;
import offset.nodes.client.virtual.model.jcr.NodeReader;
import offset.nodes.client.virtual.model.jcr.NodeWriter;
import offset.nodes.client.dialog.newnode.model.NameProvider;
import offset.nodes.client.dialog.newnode.model.NameProvider;
import offset.nodes.client.vdialog.model.PrintDocumentHandler;
import offset.nodes.client.vdialog.view.instance.TemplateInstancePanel;
import offset.nodes.client.vdialog.view.instance.VirtualFolderInstancePanel;
import offset.nodes.client.vdialog.view.instance.VirtualPageInstancePanel;

/**
 *
 * @author Walter Lütgenau
 */
public class NewTemplateInstanceConfiguration implements DetailPanelTreeConfiguration {

    JTree tree;
    Server server;
    DetailPanelTreeNodeType[] nodeTypes;
    NameProvider templateNameProvider;
    String templateInstancePath;
    Node rootNode = null;

    public NewTemplateInstanceConfiguration(Server server, NameProvider templateNameProvider, String templateInstancePath) {
        this.server = server;
        this.templateNameProvider = templateNameProvider;
        this.templateInstancePath = templateInstancePath;
        this.nodeTypes = new DetailPanelTreeNodeType[]{
            new TemplateInstance(), new VirtualFolder(), new VirtualPage()
        };
    }

    protected DefaultMutableTreeNode wrapNodes(SimpleNode rootNode) {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootNode);
        NodeIterator ni = rootNode.getNodes();
        while (ni.hasNext()) {
            Node child = ni.nextNode();
            root.add(wrapNodes((SimpleNode) child));
        }

        return root;
    }

    public void setupTree() {
        NewTemplateInstance.Request request = new NewTemplateInstance.Request();
        request.setTemplatePath(templateNameProvider.getObjectName());
        request.setTemplateInstancePath(templateInstancePath);

        NewTemplateInstance.Response response = null;
        try {
            response = (NewTemplateInstance.Response) server.sendRequest(request);

            InputStream in = new ByteArrayInputStream(response.getConfiguration().getBytes());
            NodeReader reader = new NodeReader(new TemplateInstanceNodeFactory());
            rootNode = reader.read(in);
            ((DefaultTreeModel) tree.getModel()).setRoot(wrapNodes((SimpleNode) rootNode));
            tree.setSelectionRow(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void init(JTree tree, JToolBar toolBar, JMenuBar menu) {
        this.tree = tree;
        setupTree();
    }

    public Object getResult() {
        return ((DefaultTreeModel) tree.getModel()).getRoot();
    }

    protected DetailPanelTreeNodeType getNodeType(String name) {
        for (int i = 0; i < nodeTypes.length; i++) {
            if (nodeTypes[i].getName().equals(name)) {
                return nodeTypes[i];
            }
        }
        return null;
    }

    public void insertNodeAt(DefaultMutableTreeNode parent, int position, String typeName) {
    }

    public void removeNode(DefaultMutableTreeNode remove) {
    }

    public void writeTextualRepresentation(Document document, ResourceBundle bundle) {
        NodeWriter writer = new NodeWriter(rootNode, new PrintDocumentHandler(document));
        try {
            writer.write();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void cancelNodeModification(DetailPanelTreeNodeType type) {
        TreePath path = tree.getSelectionPath();
        if (path == null) {
            return;
        }

        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        TreeNodeUserObject userObject = (TreeNodeUserObject) node.getUserObject();
        if (userObject == null) {
            return;
        }

        for (int i = 0; i < nodeTypes.length; i++) {
            if (nodeTypes[i].getName().equals(userObject.getType())) {
                TreeNodePanel panel = (TreeNodePanel) nodeTypes[i].getDetailPanel();
                panel.setPanel(userObject);
                break;
            }
        }
    }

    public void acceptNodeModification(DetailPanelTreeNodeType type) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getSelectionModel().getLeadSelectionPath().getLastPathComponent();
        node.setUserObject(((TreeNodePanel) type.getDetailPanel()).getUserObject());
    }

    public DetailPanelTreeConfiguration getModel() {
        return this;
    }

    class TemplateInstance implements DetailPanelTreeNodeType {

        ImageIcon templateInstanceIcon = new ImageIcon(NewTemplateInstanceConfiguration.class.getResource("/offset/nodes/client/dialog/view/resources/template.png"));
        TemplateInstancePanel panel = new TemplateInstancePanel(server);

        public String getName() {
            return Constants.TYPE_TEMPLATE_INSTANCE;
        }

        public JPanel getDetailPanel() {
            return panel;
        }

        public Icon getIcon() {
            return templateInstanceIcon;
        }

        public TreeNodeUserObject createUserObject() {
            return null;
        }
    
        public boolean canAccept(String typeName) {
            return true;
        }
}

    class VirtualFolder implements DetailPanelTreeNodeType {

        Icon folderIcon = UIManager.getIcon("Tree.closedIcon");
        VirtualFolderInstancePanel panel = new VirtualFolderInstancePanel(server);

        public String getName() {
            return Constants.TYPE_VIRTUAL_FOLDER_INSTANCE;
        }

        public JPanel getDetailPanel() {
            return panel;
        }

        public Icon getIcon() {
            return folderIcon;
        }

        public TreeNodeUserObject createUserObject() {
            return null;
        }
   
        public boolean canAccept(String typeName) {
            return true;
        }
 }

    class VirtualPage implements DetailPanelTreeNodeType {

        ImageIcon pageIcon = new ImageIcon(NewTemplateInstanceConfiguration.class.getResource("/offset/nodes/client/dialog/view/resources/file.png"));
        VirtualPageInstancePanel panel = new VirtualPageInstancePanel(server);

        public String getName() {
            return Constants.TYPE_VIRTUAL_PAGE_INSTANCE;
        }

        public JPanel getDetailPanel() {
            return panel;
        }

        public Icon getIcon() {
            return pageIcon;
        }

        public TreeNodeUserObject createUserObject() {
            return null;
        }
   
        public boolean canAccept(String typeName) {
            return true;
        }
 }

    public DetailPanelTreeNodeType[] getNodeTypes() {
        return nodeTypes;
    }
}
